package com.gzhryc.jdbc.utils;

import java.util.Calendar;
import java.util.Date;

public class DateTools {

	public static int differenceYear(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		return (cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR));
	}

	/**
	 * 计算两个时间相差多少月
	 *
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int differenceMonth(Date date1, Date date2) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		int month = cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);
		int yearToMonth = (cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR)) * 12;
		return yearToMonth + month;
	}
	
	public static boolean isSameMonth(final Date date1, final Date date2) {
		if (date1 == null || date2 == null) {
			throw new IllegalArgumentException("The date must not be null");
		}
		final Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		final Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
				&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH));
	}

	public static boolean isSameYear(final Date date1, final Date date2) {
		if (date1 == null || date2 == null) {
			throw new IllegalArgumentException("The date must not be null");
		}
		final Calendar cal1 = Calendar.getInstance();
		cal1.setTime(date1);
		final Calendar cal2 = Calendar.getInstance();
		cal2.setTime(date2);
		return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR));
	}
}
